package com.cbgolf.oa.service;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.cbgolf.oa.app.App;
import com.cbgolf.oa.entity.LatLon;
import com.cbgolf.oa.manager.LocationManager.ILocationWaiter;
import com.cbgolf.oa.util.TextUtil;

/**
 * @author lq
 * @date 2018/5/3
 */

public class LocationService extends Service {

  private static final String TAG = LocationService.class.getSimpleName();

  private static AMapLocationClient locationClient = null;
  private static double lat;
  private static double lon;
  public static LatLng lastLatlng;
  public static LatLng newLatlng;
  private static LatLon mLatlon;
  private static String city;
  private static String address;
  private static String locationType = "网络定位";
  private static ILocationWaiter mWorker;

  public static final int LOCATION_TIME = 5000;
  public static final int LOCATION_TIME_OUT = 5000;
  public static final int LOCATION_DIS = 5;
  /**
   * 定位监听
   */
  public static AMapLocationListener listener;

  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    createLocation();
  }

//  //声明mlocationClient对象
//  public AMapLocationClient mlocationClient;
//  //声明mLocationOption对象
//  public AMapLocationClientOption mLocationOption = null;


  private void createLocation() {
//    mlocationClient = new AMapLocationClient(this);
////初始化定位参数
//    mLocationOption = new AMapLocationClientOption();
////设置定位监听
//    mlocationClient.setLocationListener(this);
////设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
//    mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
////设置定位间隔,单位毫秒,默认为2000ms
//    mLocationOption.setInterval(2000);
////设置定位参数
//    mlocationClient.setLocationOption(mLocationOption);
//// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
//// 在定位结束后，在合适的生命周期调用onDestroy()方法
//// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
////启动定位
//    mlocationClient.startLocation();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    startLocation();
    return super.onStartCommand(intent, flags, startId);
  }

  public static void startLocation() {
    if (null == locationClient) {
      initLocation();
    } else {
      locationClient.startLocation();
    }
  }

  public static void stopLocation() {
    if (null != locationClient) {
      try {
        locationClient.stopLocation();
        locationClient.unRegisterLocationListener(listener);
        locationClient.onDestroy();
        locationClient = null;
      } catch (Exception e) {

      }
    }
  }

  public static boolean isStoped() {
    return null == locationClient || !locationClient.isStarted();
  }

  public static void setWorker(ILocationWaiter worker) {
    mWorker = worker;
  }

  @Override
  public boolean bindService(Intent service, ServiceConnection conn, int flags) {
    return super.bindService(service, conn, flags);
  }

  @Override
  public void onDestroy() {
    if (null != locationClient) {
      locationClient.stopLocation();
      locationClient.unRegisterLocationListener(listener);
      locationClient.onDestroy();
      locationClient = null;
    }
    super.onDestroy();
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    onDestroy();
  }

  @Override
  public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);
  }

  @Override
  public boolean stopService(Intent name) {
    if (null != locationClient) {
      locationClient.stopLocation();
      locationClient.unRegisterLocationListener(listener);
      locationClient.onDestroy();
      locationClient = null;
    }
    return super.stopService(name);
  }

  public static LatLon getLatlon() {
    return mLatlon;
  }

  public static double getLat() {
    return lat;
  }

  public static double getLon() {
    return lon;
  }

  public static String getCity() {
    return city;
  }

  public static String getLocationType() {
    return locationType;
  }

  public static String getAddress() {
    return address;
  }

  private static String getType(int type) {
    String res = "网络定位";
    switch (type) {
      case 5:
        res = "网络定位";
        break;
      case 1:
        res = "GPS定位";
        break;
      case 8:
        res = "离线定位";
        break;
      default:
        break;
    }
    return res;
  }

  public class LocationBinder extends Binder {

    public LocationService getService() {
      return LocationService.this;
    }
  }

  /**
   * 初始化定位
   *
   * @author hongming.wang
   * @since 2.8.0
   */
  private static void initLocation() {
    //初始化client
    locationClient = new AMapLocationClient(App.getContext());
    //设置定位参数
    locationClient.setLocationOption(getDefaultOption());
    // 设置定位监听
    locationClient.setLocationListener(getLocationListener());
    locationClient.startLocation();
  }

  private static AMapLocationListener getLocationListener() {
    if (null == listener) {
      listener = aMapLocation -> {
        if (aMapLocation != null) {
          if (aMapLocation.getErrorCode() == 0) {
//            aMapLocation.getAccuracy();//获取精度信息
            if (lat > 0 && lon > 0) {
              lastLatlng = new LatLng(lat, lon);
            }
            lat = aMapLocation.getLatitude();
            lon = aMapLocation.getLongitude();
            newLatlng = new LatLng(lat, lon);
            mLatlon = new LatLon(lat, lon);
            address = aMapLocation.getAddress();
            city = TextUtil.getCity(aMapLocation.getCity());
            locationType = getType(aMapLocation.getLocationType());
            if (null != mWorker) {
              mWorker.locationSuccess(aMapLocation);
            }
          } else {
            if (null != mWorker) {
              mWorker.locationFail();
            }
          }
        }
      };
    }
    return listener;

  }

  /**
   * 默认的定位参数
   *
   * @author hongming.wang
   * @since 2.8.0
   */
  private static AMapLocationClientOption getDefaultOption() {
    AMapLocationClientOption mOption = new AMapLocationClientOption();
    mOption.setLocationMode(
        AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
    mOption.setGpsFirst(true);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
    mOption.setHttpTimeOut(LOCATION_TIME_OUT);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
    mOption.setInterval(LOCATION_TIME);//可选，设置定位间隔。默认为2秒
    mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
    mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
//    mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
    AMapLocationClientOption.setLocationProtocol(
        AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
    mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
    //设置是否强制刷新WIFI，默认为强制刷新
    mOption.setWifiActiveScan(true);
    return mOption;
  }

  /**
   * 判断两个点之间的距离大于规定的距离
   */
  public static boolean isOutDis(LatLng last, LatLng news) {
    if (last == null) {
      return true;
    }
    float mi = AMapUtils.calculateLineDistance(last, news);
    if (mi > LOCATION_DIS) {
      return true;
    } else {
      return false;
    }
  }

}
